from django.db import models
from django.db.models import Q
from api.logics import *
from api.models import *
from api.models.Choices.choices_env import V_TYPE

class envVar(auto_id):
    '''environment variable (环境变量)
        
    Attribute (属性): 
        key: variable name.
        name: environment variable name.
        desc: environment variable description.
        var_type: environment variable type, choices cls (api.models.Choices.choices_env.V_TYPE)
        var_len_limint: max length environment variable value.
        is_local: environment variable state, false is local, true is remote.
    '''
    key = models.CharField(max_length=64, db_index=True, help_text="var name")
    name = models.CharField(max_length=64, help_text="env var name")
    desc = models.TextField(help_text="var description")
    var_type = models.IntegerField(
        choices=V_TYPE.choices, default=V_TYPE.STR, help_text="value type")
    var_len_limit = models.IntegerField(default=1, help_text="value length")
    var_value = models.TextField(help_text="value")
    is_local = models.BooleanField(
        default=False, help_text="local variable state, default local.")

    @staticmethod
    def get_by_key(k):
        result = None
        try:
            result = envVar.objects.get(key=k)
            if result.is_local:
                # to get remote value.
                pass
        except:
            pass
        return result

    @staticmethod
    def transformation(v:str, t):
        assert isinstance(t,V_TYPE), "t error, it is envVar.V_TYPE cls."
        try:
            # to transformation
            if t == V_TYPE.STR:
                v= str(v)
            elif t == V_TYPE.NUM:
                v= int(v)
            elif t == V_TYPE.LIST:
                if v.__contains__(' '):
                    v= v.split(' ')
                else:
                    err_msg = "v(%s) value error, transformation t(%s) must require split char(space)." % (v,t)
                    raise ValueError(err_msg)
            elif t == V_TYPE.BOOL:
                m_v= v.upper()
                if m_v=="NULL" or m_v=='NONE' or m_v=="" or m_v=="0":
                    return False
                else:
                    if m_v:
                        return True
                    else:
                        return False
            elif t == V_TYPE.DATE:
                pass
            elif t == V_TYPE.TIME:
                pass
            elif t == V_TYPE.DATE_TIME:
                pass
            else:
                err_msg = "t(%s) type error, see choices_env.V_TYPE" % t
                raise ValueError(err_msg)
            return v
        except Exception as e:
            raise e
